package capstoneproject.dudiachi.Main;

import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class GetBitmapFromAsset {
	
	public static Bitmap getBitmapFromAssetGV(Activity activity, String strName) throws IOException {
		
		AssetManager assetManager = activity.getAssets();
		
		BitmapFactory.Options options = new BitmapFactory.Options();
		InputStream istr = assetManager.open("img/" + strName);
		BitmapFactory.decodeStream(istr, null, options);
		
		final int REQUIRED_SIZE = 70;
		int width_tmp=options.outWidth, height_tmp=options.outHeight;
		int scale = 1;
		while (true) {
			if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
				break;
			width_tmp /= 2;
			height_tmp /= 2;
			scale *= 2;
		}
		BitmapFactory.Options op = new BitmapFactory.Options();
		op.inSampleSize = scale;
		istr = assetManager.open("img/" + strName);
		Bitmap bitmap = BitmapFactory.decodeStream(istr, null, op);
		

//		Bitmap bitmap = null;
//		Bitmap bitmap = BitmapFactory.decodeStream(istr, null, options);
//		finalBitmap = Bitmap.createBitmap(bitmap);
//		for(options.inSampleSize = 1; options.inSampleSize <= 32 ; options.inSampleSize++){
//			try{
//				bitmap = BitmapFactory.decodeStream(istr, null, options);
//				Log.d("SUCCESSFULLY", "Decode successfully at sample size: " + options.inSampleSize);
//				break;
//			}catch(OutOfMemoryError outOfMemoryError){
//				Log.e("ERROR_OUT_MEMORY", "out of memory while reading sample size " + options.inSampleSize + " retrying with higher value");
//			}
//		}
		
			
		return bitmap;
	}
	

	public static Bitmap getBitmapFromAsset(Activity activity, String strName) throws IOException {
		
		AssetManager assetManager = activity.getAssets();
		
		BitmapFactory.Options options = new BitmapFactory.Options();
		InputStream istr = assetManager.open("img/" + strName);
		Bitmap bitmap = BitmapFactory.decodeStream(istr, null, options);
		
//		Bitmap bitmap = null;
//		Bitmap bitmap = BitmapFactory.decodeStream(istr, null, options);
//		finalBitmap = Bitmap.createBitmap(bitmap);
//		for(options.inSampleSize = 1; options.inSampleSize <= 32 ; options.inSampleSize++){
//			try{
//				bitmap = BitmapFactory.decodeStream(istr, null, options);
//				Log.d("SUCCESSFULLY", "Decode successfully at sample size: " + options.inSampleSize);
//				break;
//			}catch(OutOfMemoryError outOfMemoryError){
//				Log.e("ERROR_OUT_MEMORY", "out of memory while reading sample size " + options.inSampleSize + " retrying with higher value");
//			}
//		}
		
			
		return bitmap;
	}
}
